﻿using System;
using System.Collections.Generic; 
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient; 
using Telerik.Web.UI; 
using System.Web.Script.Services;
using System.Web.Services;
using Adex;
using MediaMonitor.Common;
using MediaMonitor.Controls;
using System.Collections;

namespace MediaMonitor.Users
{
    public partial class Report_Internet_Filter : Adex.BasePage
    {
        DateTime sDate = DateTime.MinValue, eDate = DateTime.MinValue;
        int mediaTypeCode = 0;
        string mediaCodes = "", categoryCode = "", productCode="";
        int sectorCode = 0, subSectorCode = 0, subSector2Code = 0;
        int advertiserCode = 0, brandCode = 0, versionCode = 0, agencyCode = 0;
        int sTime = 0, eTime = 0;
        int sCol = 0, eCol = 0;
        string sInch = "0", eInch = "";
        int colorCode = 0;
        int pageNumber = 0;
        int sPrice = 0, ePrice = 0;
        bool firstAppearanceOnly = false;
        bool DownloadOnly = false;
        bool DownloadOnlyProduct = false;
        bool DownloadOnlyAdvertiser = false;

        private string sector = "", subsector = "", category = "", advertiser = "", agency = "";
        private string product = "", version = "",days="";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Utility.AddDateControlToPage(this.Page);


                SetCalendarDates();
                FillMediaTypes();
                FillSectors();
                FillAdvertisers();
                FillAgencies();
                FillSubSectors();
                FillCategories();

                FillColorCodes();
                FillColumns();

                //switch (AppUser.GetCountry())
                //{
                //    case 58:
                //        {
                //            lstFields.Items.FindByValue("Wide").Text = "Inches";
                //            break;
                //        }
                //    case 218:
                //        {
                //            lstFields.Items.FindByValue("Wide").Text = "Centimeters";
                //            break;
                //        }
                //}

                Session["INTERNETUserWriteProductName"] = 0;
                Session["INTERNETVerUserWriteProductName"] = 0;

                Session["INTERNETUserWriteProductNameText"] = "";
                Session["INTERNETVerUserWriteProductNameText"] = "";

            }
        }

        private void SetCalendarDates()
        {


            DataTable dt = InternetLog.Query().DISTINCT().SetSelectList("RFDate").ExecuteDataSet().Tables[0];


            foreach (DataRow dr in dt.Rows)
            {

                RadCalendarDay d1 = new RadCalendarDay(calS);
                d1.Date = Utility.ToDateTime(dr["RFDate"]);
                d1.IsDisabled = false;
                d1.IsSelectable = true;

                d1.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d1.ItemStyle.ForeColor = System.Drawing.Color.White;

                calS.SpecialDays.Add(d1);

                RadCalendarDay d2 = new RadCalendarDay(calE);
                d2.Date = Utility.ToDateTime(dr["RFDate"]);
                d2.IsDisabled = false;
                d2.IsSelectable = true;

                d2.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d2.ItemStyle.ForeColor = System.Drawing.Color.White;


                calE.SpecialDays.Add(d2);
            }



        }


        protected void calS_ViewChanged(object sender, EventArgs e)
        {
            for (DateTime dt = calS.CalendarView.ViewStartDate; dt <= calS.CalendarView.ViewEndDate; dt.AddDays(1))
            {

            }
        }


        private static DataSet GetLookupDataSet()
        {

            if (HttpContext.Current.Cache["dsLookUpByUser_IN_" + AppUser.CurrUserID.ToString()] == null)
            {
                //Get Lookup Tables filtered by User / Company settings
                DataSet ds = SPs.GetLookupTables(AppUser.CurrUserID, "IN").GetDataSet();
                ds.Tables[0].TableName = "MediaType";
                ds.Tables[1].TableName = "Media";
                ds.Tables[2].TableName = "Agency";
                ds.Tables[3].TableName = "Advertiser";
                ds.Tables[4].TableName = "Brand";
                ds.Tables[5].TableName = "Sector";
                ds.Tables[6].TableName = "SubSector";
                ds.Tables[7].TableName = "Category";
                ds.Tables[8].TableName = "Product";
                ds.Tables[9].TableName = "ProdVersion";
                
                HttpContext.Current.Cache.Insert("dsLookUpByUser_IN_" + AppUser.CurrUserID.ToString(), ds, null, DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                return ds;

            }
            else
            {
                return ((DataSet)(HttpContext.Current.Cache["dsLookUpByUser_IN_" + AppUser.CurrUserID.ToString()]));
            }
        }





        #region FillLists


        private void FillSectors()
        {
            DataTable dt = GetLookupDataSet().Tables[5];

            string filter = "1=1";
            switch (lstMediaType.SelectedValue)
            {
                case "1":
                    {
                        filter += " AND MediaType = 'TVCR' AND  TV = 1";
                        break;
                    }

                case "3":
                    {
                        filter += " AND MediaType = 'TVCR'  AND RD = 1";
                        break;
                    }
                case "5":
                    {
                        filter += " AND MediaType = 'TVCR'  AND CB = 1";
                        break;
                    }
                case "6":
                    {
                        filter += " AND MediaType = 'PR' AND PR = 1";
                        break;
                    }
                case "7":
                    {
                        filter += " AND MediaType = 'OD' AND OD = 1";
                        break;
                    }
                case "8":
                    {
                        filter += " AND MediaType = 'NS' AND NS = 1";
                        break;
                    }
                case "9":
                    {
                        filter += " AND MediaType = 'IN' AND [IN] = 1";
                        break;
                    }
            }

            string sort = "SectorName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);
            DataTable dtcolumns = dv.ToTable(true, "SectorID", "SectorName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "SectorName");
                lstSector.DataSource = dtcolumns;
                lstSector.DataBind();
            }
            lstSector.Items.Insert(0, new ListItem("- ALL -", "0"));
        }



        public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
        {
            Hashtable hTable = new Hashtable();
            ArrayList duplicateList = new ArrayList();

            //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
            //And add duplicate item value in arraylist.
            foreach (DataRow drow in dTable.Rows)
            {
                if (hTable.Contains(drow[colName]))
                    duplicateList.Add(drow);
                else
                    hTable.Add(drow[colName], string.Empty);
            }

            //Removing a list of duplicate items from datatable.
            foreach (DataRow dRow in duplicateList)
                dTable.Rows.Remove(dRow);

            //Datatable which contains unique records will be return as output.
            return dTable;
        }


        private void FillSubSectors()
        {
            DataTable dt = GetLookupDataSet().Tables[6];

            string filter = "1=1";
            switch (lstMediaType.SelectedValue)
            {
                case "1":
                    {
                        filter += " AND MediaType = 'TVCR'  AND TV = 1";
                        break;
                    }

                case "3":
                    {
                        filter += " AND MediaType = 'TVCR'  AND RD = 1";
                        break;
                    }
                case "5":
                    {
                        filter += " AND MediaType = 'TVCR'  AND CB = 1";
                        break;
                    }
                case "6":
                    {
                        filter += " AND MediaType = 'PR' AND PR = 1";
                        break;
                    }
                case "7":
                    {
                        filter += " AND MediaType = 'OD' AND OD = 1";
                        break;
                    }
                case "8":
                    {
                        filter += " AND MediaType = 'NS' AND NS = 1";
                        break;
                    }
                case "9":
                    {
                        filter += " AND MediaType = 'IN' AND [IN] = 1";
                        break;
                    }
            }

            filter += lstSector.SelectedValue != "0" ? " AND SectorID=" + lstSector.SelectedValue : "";

            string sort = "SubSectorName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);


            DataTable dtcolumns = dv.ToTable(true, "SubSectorID", "SubSectorName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "SubSectorName");
              
                lstSubSector.DataSource = dtcolumns;
                lstSubSector.DataBind();

                lstSubSector2.DataSource = dtcolumns;
                lstSubSector2.DataBind();
            }

            lstSubSector.Items.Insert(0, new ListItem("- ALL -", "0"));
            lstSubSector2.Items.Insert(0, new ListItem("- ALL -", "0"));
        }

        private void FillCategories()
        {
            DataTable dt = GetLookupDataSet().Tables[7];

            string filter = "1=1";
            switch (lstMediaType.SelectedValue)
            {
                case "1":
                    {
                        filter += " AND MediaType='TVCR' AND TV = 1";
                        break;
                    }

                case "3":
                    {
                        filter += " AND MediaType='TVCR' AND RD = 1";
                        break;
                    }
                case "5":
                    {
                        filter += " AND MediaType='TVCR' AND CB = 1";
                        break;
                    }
                case "6":
                    {
                        filter += " AND MediaType='PR' AND PR = 1";
                        break;
                    }
                case "7":
                    {
                        filter += " AND MediaType='OD' AND OD = 1";
                        break;
                    }
                case "8":
                    {
                        filter += " AND MediaType='NS' AND NS = 1";
                        break;
                    }
                case "9":
                    {
                        filter += " AND MediaType='IN' AND [IN] = 1";
                        break;
                    }
            }

            // filter += lstSector.SelectedValue != "0" ? " AND SectorCode=" + lstSector.SelectedValue : "";
            filter += lstSubSector.SelectedValue != "0" ? " AND SubSectorID=" + lstSubSector.SelectedValue : "";

            string sort = "CategoryName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

            DataTable dtcolumns = dv.ToTable(true, "CategoryID", "CategoryName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "CategoryName");
                chkCategory.DataSource = dtcolumns;
                chkCategory.DataBind();
            }
           
        }

        private void FillAdvertisers()
        {
            DataTable dt = GetLookupDataSet().Tables[3];

            string filter = "1=1";
            switch (lstMediaType.SelectedValue)
            {
                case "1":
                    {
                        filter += " AND MediaType='TVCR' AND TV = 1";
                        break;
                    }

                case "3":
                    {
                        filter += " AND MediaType='TVCR' AND RD = 1";
                        break;
                    }
                case "5":
                    {
                        filter += " AND MediaType='TVCR' AND CB = 1";
                        break;
                    }
                case "6":
                    {
                        filter += " AND MediaType='PR' AND PR = 1";
                        break;
                    }
                case "7":
                    {
                        filter += " AND MediaType='OD' AND OD = 1";
                        break;
                    }
                case "8":
                    {
                        filter += " AND MediaType='NS' AND NS = 1";
                        break;
                    }
                case "9":
                    {
                        filter += " AND MediaType='IN' AND [IN] = 1";
                        break;
                    }
            }

            string sort = "AdvertiserName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

            lstAdvertiser.DataSource = dv;
            lstAdvertiser.DataBind();

            lstAdvertiser.Items.Insert(0, new ListItem("- ALL -", "0"));
        }

        private void FillAgencies()
        {
            DataTable dt = GetLookupDataSet().Tables[2];

            string filter = "1=1";
            switch (lstMediaType.SelectedValue)
            {
                case "1":
                    {
                        filter += " AND MediaType='TVCR' AND TV = 1";
                        break;
                    }

                case "3":
                    {
                        filter += " AND MediaType='TVCR' AND RD = 1";
                        break;
                    }
                case "5":
                    {
                        filter += " AND MediaType='TVCR' AND CB = 1";
                        break;
                    }
                case "6":
                    {
                        filter += " AND MediaType='PR' AND PR = 1";
                        break;
                    }
                case "7":
                    {
                        filter += " AND MediaType='OD' AND OD = 1";
                        break;
                    }
                case "8":
                    {
                        filter += " AND MediaType='NS' AND NS = 1";
                        break;
                    }
                case "9":
                    {
                        filter += " AND MediaType='IN' AND [IN] = 1";
                        break;
                    }
            }
            string sort = "AgencyName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

            dv.RowFilter = "AgencyName IS NOT NULL AND AgencyName <> ''";


            DataTable dtcolumns = dv.ToTable(true, "AgencyID", "AgencyName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "AgencyName");
                lstAgency.DataSource = dtcolumns;
                lstAgency.DataBind();
            }
            lstAgency.Items.Insert(0, new ListItem("- ALL -", "0"));
       }

        protected void lstSector_Changed(object sender, EventArgs e)
        {
            FillSubSectors();
            FillCategories();

        }

        protected void lstSubSector_Changed(object sender, EventArgs e)
        {
            FillCategories();

        }

        #endregion


        #region Fill Media

        private void FillMediaTypes()
        {

            lstMediaType.DataSource = GetLookupDataSet().Tables["MediaType"];
            lstMediaType.DataBind();


            FillMedia(Utility.ToInt(lstMediaType.SelectedValue));
        }

        private void FillMedia(int MediaTypeCode)
        {


            if (MediaTypeCode > 0)
                lstMedia.DataSource = new DataView(GetLookupDataSet().Tables["Media"], "MediaTypeCode=" + MediaTypeCode.ToString(), "MediaName", DataViewRowState.OriginalRows);
            else
                lstMedia.DataSource = GetLookupDataSet().Tables["Media"];


            lstMedia.DataBind();

          

        }


        protected void lstMediaType_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillMedia(Utility.ToInt(lstMediaType.SelectedValue));

            FillAdvertisers();
            FillAgencies();

        }



        #endregion



        #region AutoComplete Functions


        [WebMethod]
        public static string[] AutoComplete_FillBrand(string prefixText, int count)
        {
            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[4];

            string filter = "1=1 ";
            string filterwrite = "1=1 ";

            filter += " AND MediaType='IN' AND BrandName LIKE '" + prefixText + "%'";
            filterwrite += " AND MediaType='IN' AND BrandName ='" + prefixText + "'";

            DataRow[] drsUserWrite = dt.Select(filterwrite);
            try
            {
                if (drsUserWrite.Length == 1) //If user write and that item is in database
                {
                    HttpContext.Current.Session["INTERNETUserWriteProductName"] = drsUserWrite[0][0];
                    HttpContext.Current.Session["INTERNETUserWriteProductNameText"] = drsUserWrite[0][2];

                }
                else
                {
                    HttpContext.Current.Session["INTERNETUserWriteProductName"] = -1;
                    HttpContext.Current.Session["INTERNETUserWriteProductNameText"] = "";
                }
            }
            catch { }



            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["BrandName"].ToString(), dr["BrandID"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        [WebMethod]
        public static string[] AutoComplete_FillProduct(string prefixText, int count, string contextKey)
        {
            //contextKey is brandCode


            string filter = "1=1 ";
            filter += " AND MediaType='IN' AND ProductName LIKE '" + prefixText + "%'";

            //get brand 

            if (contextKey != null && contextKey != "" && contextKey != "0")
            {
                filter += " AND BrandID = " + contextKey;
            }

            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[8];

            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["ProductName"].ToString(), dr["ProductID"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        [WebMethod]
        public static string[] AutoComplete_FillVersion(string prefixText, int count, string contextKey)
        {
           


            string filter = "1=1 ";
            string filterwrite = "1=1 ";
            filter += " AND MediaType='IN' AND ProdVersionName LIKE '" + prefixText + "%'";
            filterwrite += " AND MediaType='IN' AND ProdVersionName ='" + prefixText + "'";
            

            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[9];


            DataRow[] drsUserWrite = dt.Select(filterwrite);
            try
            {
                if (drsUserWrite.Length == 1) //If user write and that item is in database
                {
                    HttpContext.Current.Session["INTERNETVerUserWriteProductName"] = drsUserWrite[0][0];
                    HttpContext.Current.Session["INTERNETVerUserWriteProductNameText"] = drsUserWrite[0][2];

                }
                else
                {
                    HttpContext.Current.Session["INTERNETVerUserWriteProductName"] = -1;
                    HttpContext.Current.Session["INTERNETVerUserWriteProductNameText"] = "";
                }
            }
            catch { }

            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["ProdVersionName"].ToString(), dr["ProdVersionID"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }

        #endregion




        protected void FillColorCodes()
        {
            DataTable dtCol = PressLog.Query().SetSelectList("ColorCode").DISTINCT().ExecuteDataSet().Tables[0];
            lstColorCode.DataSource = dtCol;
            lstColorCode.DataTextField = "ColorCode";
            lstColorCode.DataValueField = "ColorCode";
            lstColorCode.DataBind();

            lstColorCode.Items.Insert(0, new ListItem("Any", "0"));
        }

        protected void FillColumns()
        {

            lstColumnsS.Items.Clear();
            for (int i = 0; i <= 50; i++)
            {
                if (i <= 30)
                {

                    lstColumnsS.Items.Add(new ListItem(i.ToString(), i.ToString()));
                    lstColumnsE.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }

                lstInchesS.Items.Add(new ListItem(i.ToString(), i.ToString()));
                lstInchesE.Items.Add(new ListItem(i.ToString(), i.ToString()));

            }

            Utility.SelectListItemByText(lstColumnsE, "30");
            Utility.SelectListItemByText(lstInchesE, "50");
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {

            DownloadOnly = chkDownload.Checked;
            if (DownloadOnly && (hdnCategoryIds.Value == ""))
            {
                AjaxFuncs.MsgBox(this.Page,
                                 "To download all the videos, audios, or images related to your category, u must select the category.");
                return;
            }

            DownloadOnlyAdvertiser = chkDownloadAdvertiser.Checked;
            if (DownloadOnlyAdvertiser && (lstAdvertiser.SelectedItem.Text == "- ALL -"))
            {
                AjaxFuncs.MsgBox(this.Page,
                                 "To download all the videos, audios, or images related to your advertiser, u must select the advertiser.");
                return;
            }


            bool tmp1 = DateTime.TryParse(calS.SelectedDate.ToShortDateString(), out sDate);
            bool tmp2 = DateTime.TryParse(calE.SelectedDate.ToShortDateString(), out eDate);

            if (sDate < Utility.ToDateTime("01/01/2000"))         //Calendar Start Date
                sDate = Utility.ToDateTime("01/01/2000");

            if (eDate < Utility.ToDateTime("01/01/2000"))        //Calendar End Date
                eDate = Utility.ToDateTime("01/01/2000");


            mediaTypeCode = Utility.ToInt(lstMediaType.SelectedValue); //Media Type

            foreach (ListItem itm in lstMedia.Items) //Channel / Media Name
            {
                if (itm.Selected)
                    mediaCodes += itm.Value + ",";
            }
            mediaCodes = mediaCodes.TrimEnd(',');


            sectorCode = Utility.ToInt(lstSector.SelectedValue);       //Sector
            subSectorCode = Utility.ToInt(lstSubSector.SelectedValue); //SubSector
            categoryCode = hdnCategoryIds.Value;   //Category

            advertiserCode = Utility.ToInt(lstAdvertiser.SelectedValue);//Advertiser 
            agencyCode = Utility.ToInt(lstAgency.SelectedValue);        //Agency 



            sector = lstSector.SelectedItem.Text;
            subsector = lstSubSector.SelectedItem.Text;
            category = lblSelectedCategory.Text;
            advertiser = lstAdvertiser.SelectedItem.Text;
            agency = lstAgency.SelectedItem.Text;

            //brandCode = Utility.ToInt(acBrand.SelectedValue);

            if (Utility.ToInt(acBrand.SelectedValue) == 0) //not selected by user
            {
                try
                {
                    if (Convert.ToInt32(Session["INTERNETUserWriteProductName"].ToString()) != 0)
                    {

                        brandCode = Utility.ToInt(Session["INTERNETUserWriteProductName"].ToString());
                        product = Session["INTERNETUserWriteProductNameText"].ToString();
                    }
                }
                catch { }

            }
            else
            {
                brandCode = Utility.ToInt(acBrand.SelectedValue);
                TextBox txtBrand = (TextBox)acBrand.FindControl("tbAutoComplete");
                product = txtBrand.Text;
            }


            DownloadOnlyProduct = chkDownloadProduct.Checked;
            if (DownloadOnlyProduct && (brandCode == 0))
            {
                AjaxFuncs.MsgBox(this.Page,
                                 "To download all the videos, audios, or images related to your product, u must select the product.");
                return;
            }


            productCode = hdnProductIDs.Value;       //Product
            //versionCode = Utility.ToInt(acVersion.SelectedValue);       //Version

            if (Utility.ToInt(acVersion.SelectedValue) == 0) //not selected by user
            {
                try
                {
                    if (Convert.ToInt32(Session["INTERNETVerUserWriteProductName"].ToString()) != 0)
                    {

                        versionCode = Utility.ToInt(Session["INTERNETVerUserWriteProductName"].ToString());
                        version = Session["INTERNETVerUserWriteProductNameText"].ToString();
                    }
                }
                catch { }

            }
            else
            {
                versionCode = Utility.ToInt(acVersion.SelectedValue);
                TextBox txtVersion = (TextBox)acVersion.FindControl("tbAutoComplete");
                version = txtVersion.Text;
            }


            sTime = Utility.ToInt(txtStartTime1.Text);          // Start Time(Hide)
            eTime = Utility.ToInt(txtEndTime1.Text);            // End Time(Hide)

            sInch = lstInchesS.SelectedValue;                           //Inches From(Hide)
            eInch = lstInchesE.SelectedValue;                           //Inches To(Hide)

            colorCode = Utility.ToInt(lstColorCode.SelectedValue);      //Color Code(Hide)

            pageNumber = Utility.ToInt(tbPageNumber.Text);              //Location (Page)(Hide)


            sCol = Utility.ToInt(lstColumnsS.SelectedItem.Text);        //Columns FROM(Hide)
            eCol = Utility.ToInt(lstColumnsE.SelectedItem.Text);        //Columns To(Hide)

            sPrice = tbPriceFrom.Text != "" ? Utility.ToInt(tbPriceFrom.Text) : 0; //Price From(Hide)
            ePrice = tbPriceTo.Text != "" ? Utility.ToInt(tbPriceTo.Text) : 0;     //Price To(Hide)

            firstAppearanceOnly = chkFirstAppearance.Checked;


            //if (firstAppearanceOnly == false && (sDate == Utility.ToDateTime("01/01/2000") || eDate == Utility.ToDateTime("01/01/2000")) || eDate.Subtract(sDate).Days > 31)
            //{
            //    AjaxFuncs.MsgBox(this.Page, "You must select a date range of maximum 1 month");
            //    return;
            //}



            //if (firstAppearanceOnly && (sDate == Utility.ToDateTime("01/01/2000") || eDate.Subtract(sDate).Days != 0))
            //{
            //    AjaxFuncs.MsgBox(this.Page, "To see the first appearance of a product, u must select the Date Range of only 1 Day. i.e. Select the same date as Start and End Date.");
            //    return;
            //}


            string cols = "";

            foreach (ListItem itm in lstFields.Items) //Report Fields
            {
                if (itm.Selected)
                {
                    cols += itm.Value + ", ";
                }
            }

            if (cols.Contains(","))
                cols = cols.Substring(0, cols.LastIndexOf(","));



            Session["SearchMediaCodes_internet"] = mediaCodes;
            foreach (System.Web.UI.WebControls.ListItem itm in chklstDays.Items)
            {
                if (itm.Selected)
                    days += itm.Value + ",";
            }
            Response.Redirect(Server.UrlPathEncode(string.Format("report-internet.aspx?sd={0}&ed={1}&mtc={2}&mc={3}&s={4}&ss={5}&cc={6}&adv={7}&brnd={8}&prod={9}&ver={10}&agn={11}&st={12}&et={13}&scol={14}&ecol={15}&ccode={16}&pn={17}&sin={18}&ein={19}&sp={20}&ep={21}&fa={22}&cols={23}&down={24}&zs={25}&zss={26}&zc={27}&zad={28}&zag={29}&zp={30}&zve={31}&downpro={32}&downadv={33}&days={34}",
            sDate.ToShortDateString().Replace("/", "_"), eDate.ToShortDateString().Replace("/", "_"), mediaTypeCode, chkAllMedia.Checked, sectorCode, subSectorCode, categoryCode, advertiserCode, brandCode, productCode, versionCode, agencyCode, sTime, eTime, sCol, eCol, colorCode, pageNumber, sInch, eInch, sPrice, ePrice, firstAppearanceOnly, cols, DownloadOnly, sector, subsector, category, advertiser, agency, product, version, DownloadOnlyProduct, DownloadOnlyAdvertiser, days)));
            //Start Date{0}, End Date{1},mediaTypeCode{2},mediaCodes{3},sector{4},subsector{5},category{6},Advertiser{7},brand{8},prodcut{9},version{10},agency{11},start time{12}, end time{13},start column{14},end colums{15},color code{16}, {17},start inch {18},end inch{19},start price{20},end price{21},first apperiance{22},column{23}
           
        }
        protected void lnkCategory_Click(object sender, EventArgs e)
        {

            ModalPopupExtender3.Show();
            if (chkCategory.Items.Count == 0)
            {
                lblNoteCategory1.Visible = true;
                btnSaveCategory.Enabled = false;
                lnkProduct.Enabled = false;
            }
            else
            {
                lblNoteCategory1.Visible = false;
                btnSaveCategory.Enabled = true;
                lnkProduct.Enabled = true;
            }
            string[] str = hdnCategoryIds.Value.Split(',');

            for (int i = 0; i < str.Length; i++)
            {
                foreach (ListItem itm in chkCategory.Items)
                {
                    if (itm.Value == str[i].ToString())
                        itm.Selected = true;
                }
            }
        }
        protected void btnSaveCategory_Click(object sender, EventArgs e)
        {
            string CategoryIDs = string.Empty;
            string CategoryNames = string.Empty;
            foreach (ListItem itm in chkCategory.Items)
            {
                if (itm.Selected)
                {
                    CategoryIDs += itm.Value + ",";
                    CategoryNames += itm.Text + ", ";
                }
            }
            hdnCategoryIds.Value = CategoryIDs.TrimEnd(',');
            lblSelectedCategory.Text = CategoryNames.TrimEnd(',');
            //BindBrandsAccordingtoCategories(lblSelectedCategory.Text);
            ModalPopupExtender3.Hide();
        }
        protected void lnkProduct_Click(object sender, EventArgs e)
        {
            ModalPopupExtender4.Show();
            DataTable dt = SPs.ProductByCategory(hdnCategoryIds.Value,"IN").GetDataSet().Tables[0];
            if (dt.Rows.Count > 0)
            {
                lblNoteProduct.Visible = false;
                btnSaveProduct.Enabled = true;
                chkProduct.DataTextField = "ProductName";
                chkProduct.DataValueField = "ProductID";
                chkProduct.DataSource = dt;
                chkProduct.DataBind();
                string[] str = hdnProductIDs.Value.Split(',');

                for (int i = 0; i < str.Length; i++)
                {
                    foreach (ListItem itm in chkProduct.Items)
                    {
                        if (itm.Value == str[i].ToString())
                            itm.Selected = true;
                    }
                }
            }
            else
            {
                lblNoteProduct.Visible = true;
                btnSaveProduct.Enabled = false;
                chkProduct.Visible = false;
            }
        }
        protected void btnCancelCategory_Click(object sender, EventArgs e)
        {
            ModalPopupExtender3.Hide();
        }
        protected void btnSaveProduct_Click(object sender, EventArgs e)
        {
            string ProductIDs = string.Empty;
            string ProductNames = string.Empty;
            foreach (ListItem itm in chkProduct.Items)
            {
                if (itm.Selected)
                {
                    ProductIDs += itm.Value + ",";
                    ProductNames += itm.Text + ",";
                }
            }
            hdnProductIDs.Value = ProductIDs.TrimEnd(',');
            lblSelectedProduct.Text = ProductNames.TrimEnd(',');
            ModalPopupExtender4.Hide();
        }
        protected void btnCancelProduct_Click(object sender, EventArgs e)
        {
            ModalPopupExtender4.Hide();
        }
    }
}